package http.util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ParseUtil {
    //注意只能解析val
    public static String extractCharacters(Elements elements) {

        if (elements == null || elements.size() == 0) {
            System.out.println("解析失败: 数据可能不存在 | 页面重定向");
            return null;
        }
        System.out.println(elements);

        for (Iterator<Element> it = elements.iterator(); it.hasNext(); ) {
            Element resMessage = it.next();
            return extractCharacters(resMessage.val());
        }
        return null;
    }

    public static String extractCharacters(String string) {

        if (string == null) {
            System.out.println("解析失败: 数据可能不存在 | 页面重定向");
            return null;
        }

        Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
        StringBuilder messageStr = new StringBuilder();
        Matcher matcher = pattern.matcher(string);
        while (matcher.find()) {
            messageStr.append(matcher.group());
        }
        messageStr.append("\r\n");

        if (messageStr.length() > 0) {
            //System.out.println("解析成功: " + messageStr);
            return messageStr.toString();
        } else {
           // System.out.println("解析失败: " + "匹配不到数据");
            return null;
        }
    }

    public static String parseScript(String responseHtml) {
        if(responseHtml==null){
            return null;
        }
        Document doc = Jsoup.parse(responseHtml);
        if (doc.select("script[language]").size() == 0) {
            return null;
        }
        Element element = doc.select("script[language]").get(0);
        return extractCharacters(element.data());
    }

    public static String parseElement(String responseHtml, String element) {
        Document doc = Jsoup.parse(responseHtml);
        Elements elements = doc.select(element);
        return extractCharacters(elements);
    }

}
